﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Net;
using System.Web;
using System.Web.Routing;
using cn.Util;

namespace yq.ControllerBase
{
    /// <summary>
    /// 异常处理
    /// 请在配置文件添加500页面的跳转结点
    /// </summary>
    public class ErrorFilterAttribute : HandleErrorAttribute
    {
        public string ErrorSimple { get; set; }
       
        public ErrorFilterAttribute(string _ErrorText = "未定义错误原因")
        {
            ErrorSimple = _ErrorText;
        }

        public override void OnException(ExceptionContext filterContext)
        {
            string ErrorDetailed = "";
            var Request = filterContext.HttpContext.Request;
            var Response = filterContext.HttpContext.Response;

            //是否发生了错误
            if (filterContext.Exception == null || filterContext.ExceptionHandled)
            {
                return;
            }

            BaseController log=new BaseController();
            log.LogWriteAsyn(ErrorSimple, filterContext.Exception.ToString());

            //如果是开发模式写入异常消息
            if (yq.ControllerBase.WebConfig.IsDevelop)
            {
                ErrorDetailed = "<H2>" + ErrorSimple + "</H2><BR/>在开发模式错误提示：" + filterContext.Exception.ToString();
            }

            Response.StatusCode = 200;
            //设置异常已捕获
            filterContext.ExceptionHandled = true;
            //设置不跳到500页面
            filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;

            filterContext.Result = GetError(ErrorSimple, ErrorDetailed, filterContext.Controller);
        }


        /// <summary>
        /// 根据错误配置设置错误处理方式
        /// </summary>
        /// <param name="type"></param>
        /// <param name="errorText"></param>
        /// <param name="httpContext"></param>
        /// <param name="toUrl">当需要跳转时，指定跳转地址</param>
        /// <returns></returns>
        public static ActionResult GetError(string errorText, string errorDetailed, System.Web.Mvc.ControllerBase controller)
        {
            if (controller.ControllerContext.HttpContext.Request.IsAjaxRequest())
            {
               return new JsonResult
               {
                   Data = new ReturnValue<string>() { Status = ReturnEnum.No, ErrorSimple = errorText, ErrorDetailed = errorDetailed },
                   ContentEncoding = System.Text.Encoding.UTF8,
                   JsonRequestBehavior = JsonRequestBehavior.AllowGet
               };
            }
            else
            {
                string guid = "Guid".ExtNewGuid();
                controller.TempData[guid] = errorText;
                return new RedirectResult(yq.ControllerBase.WebConfig.Error500 + "?errorGuid=" + guid);
            }
        }

        /// <summary>
        /// 404
        /// </summary>
        /// <param name="server"></param>
        /// <param name="controller"></param>
        /// <param name="response"></param>
        public static void GetError404(HttpServerUtilityBase server, System.Web.Mvc.ControllerBase controller, HttpResponseBase response)
        {
            if (controller.ControllerContext.HttpContext.Request.IsAjaxRequest())
            {
                var rv = new ReturnValue<string>() { Status = ReturnEnum.No, ErrorSimple = "Page not found（404）" };
                server.ClearError();
                response.ClearContent();
                response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(rv));
            }
            else
            {
                response.Redirect(yq.ControllerBase.WebConfig.Error404);
            }
        }
    }
}
